package com.qy.changemachine

import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.app.custom.CustomManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.RecoverySystem
import android.os.RemoteException
import android.util.Log
import android.view.View
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.android.tools.Back
import com.android.tools.Call
import com.qy.changemachine.api.RetrofitClient
import com.qy.changemachine.util.Contants
import com.qy.changemachine.util.LogUtil
import com.qy.changemachine.util.ShellUtils
import com.qy.changemachine.util.SystemPropertiesReflector
import com.qy.changemachine.util.Utils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.io.File
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executors


class MainActivity : AppCompatActivity() {
    private lateinit var bt1: Button
    private lateinit var bt2: Button
    private lateinit var bt4: Button
    private lateinit var bt5: Button
    private lateinit var bt10: Button
    private lateinit var bt11: Button
    private lateinit var bt12: Button
    private lateinit var bt13: Button
    private lateinit var bt14: Button
    private lateinit var bt15: Button
    private lateinit var bt16: Button
    private lateinit var bt17: Button
    private lateinit var bt18: Button
    private lateinit var customManager: CustomManager
    private lateinit var utils: Utils
    private val serviceJob = Job()
    private val serviceScope = CoroutineScope(Dispatchers.IO + serviceJob)

    private var aidlCall: Call? = null
    private var initAutoJsFuture: CompletableFuture<Int>? = null
    public  val context: Context = this
    @SuppressLint("WrongConstant", "SetTextI18n", "MissingPermission")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.enableEdgeToEdge()
        customManager = getSystemService("custommanager") as CustomManager
        if (customManager != null) {
            try {
                Log.e(TAG, "data:" + customManager.testMsg)
            } catch (e: Exception) {
                Log.e(TAG, "Failed to get custommanager service Exception:" + e.message)
            }
        } else {
            Log.e(TAG, "Failed to get custommanager service.")
        }
        setContentView(R.layout.activity_main)

        utils = Utils(this, null)
        LogUtil.init(this@MainActivity)
        bt1 = findViewById(R.id.button_model_1)
        bt1.setOnClickListener({

            //@@@@@@@@@@ step 3  下载改机相关 @@@@@@@@@@@@@@@
            serviceScope.launch {
                try {
                    utils.showToast("获取下载改机地址")
                    LogUtil.d(TAG, " mainactivity-----step 1 start down change Phone----------")
                    val changPhoneResponse =
                        RetrofitClient.apiService.getChangePhoneInfo_new(Contants.changePhoneUrl)
                    utils.showToast("获取下载改机地址信息完成：" + changPhoneResponse.data.ossUrl)
                    if (changPhoneResponse.data == null || changPhoneResponse.data.ossUrl == null) {
                        utils.showToast("获取下载改机地址为空")
                        return@launch
                    }
                    utils.downLoad(changPhoneResponse.data.ossUrl, Contants.CHANGE_PHONE_PATH, true)
                    val data =
                        utils.compressString(utils.readJsonFileToString(Contants.CHANGE_PHONE_PATH))
                    if (customManager == null) {
                        utils.showToast("改机失败customManager 为空")
                    } else {
                        customManager?.setTestMsgFromZipData(data)
                        LogUtil.d(TAG, "改机成功")
                        utils.showToast("改机成功")
                        setVersionInfo()
                    }
                    LogUtil.d(TAG, "mainactivity-----step2 down change Phone end----------------")
                } catch (e: Exception) {
                    LogUtil.d(
                        TAG,
                        "mainactivity-----step3 down change Phone Exception--------${e.message}"
                    )
                }
            }
        });
        bt2 = findViewById(R.id.button_model_2)
        bt4 = findViewById(R.id.button_model_4)
        bt4.setOnClickListener(View.OnClickListener { v: View? ->

            try {
                ShellUtils.execCommand("chmod 777 " + Contants.OTA_DOWNLOAD_PATH, true);
                ShellUtils.execCommand("chown system:system " + Contants.OTA_DOWNLOAD_PATH, true);
                val update = File(Contants.OTA_DOWNLOAD_PATH)
                val progressDialog = ProgressDialog(this@MainActivity)
                progressDialog.setMessage("升级中...")
                progressDialog.show()
                Thread {
                    try {
                        Log.d(TAG, "mainactivity 校验升级包")
                        RecoverySystem.verifyPackage(update, null, null)

                        Log.d(TAG, "mainactivity 安装升级包")
                        RecoverySystem.installPackage(this@MainActivity, update)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    } finally {
                        // 在主线程中关闭加载框
                        runOnUiThread {
                            progressDialog.dismiss()
                        }
                    }
                }.start()
            } catch (e: Exception) {
                Log.d(TAG, "mainactivity-----step4 install ota Exception--------${e.message}")
            }


        })

        bt5 = findViewById(R.id.button_model_5)
        bt5.setOnClickListener(View.OnClickListener { v: View? ->
            utils.factoryReset(
                this
            )
        })


        bt10 = findViewById(R.id.button_model_10)
        bt10.setOnClickListener(View.OnClickListener { v: View? ->
            // 启动前台服务
            val serviceIntent = Intent(
                this,
                MqttForegroundService::class.java
            )
            startForegroundService(serviceIntent)
        })

        bt11 = findViewById(R.id.button_model_11)
        bt11.setOnClickListener(View.OnClickListener { v: View? ->
            utils.copyFileToSDCard(R.raw.redmi, "redmi.json")
            customManager.setTestMsgFromZipData(
                utils.compressString(
                    utils.readJsonFileToString(
                        "/data/data/com.qy.changemachine/redmi.json"
                    )
                )
            )
            setVersionInfo()
        })

        bt12 = findViewById(R.id.button_model_12)
        bt12.setOnClickListener(View.OnClickListener { v: View? ->
            utils.copyFileToSDCard(R.raw.oppo, "oppo.json")
            customManager.setTestMsgFromZipData(
                utils.compressString(
                    utils.readJsonFileToString(
                        "/data/data/com.qy.changemachine/oppo.json"
                    )
                )
            )
            setVersionInfo()
        })

        bt14 = findViewById(R.id.button_model_14)
        bt14.setOnClickListener(View.OnClickListener { v: View? ->
            serviceScope.launch {
                Contants.AUTO_JS_PATH = Contants.DATA_PATH + Contants.JS
                if (aidlCall == null) {
                    initAutoJsAidl()
                } else {
                    callAutoJsAild()
                }
            }
        })
        bt15 = findViewById(R.id.button_model_15)
        bt15.setOnClickListener(View.OnClickListener { v: View? ->

            // 创建Intent用于发送广播
            val volumeChangedIntent = Intent("android.media.VOLUME_CHANGED_ACTION")
            // 发送广播
            sendBroadcast(volumeChangedIntent)

        })
        bt16 = findViewById(R.id.button_model_16)
        bt16.setOnClickListener(View.OnClickListener { v: View? ->
            serviceScope.launch {
                Contants.AUTO_JS_PATH = Contants.DATA_PATH + Contants.SH
                if (aidlCall == null) {
                    initAutoJsAidl()
                } else {
                    callAutoJsAild()
                }
            }
        })
        bt17 = findViewById(R.id.button_model_17)
        bt17.setOnClickListener(View.OnClickListener { v: View? ->
            // 启用ADB
            SystemPropertiesReflector.set("ctl.start", "adbd")
        })
        bt18 = findViewById(R.id.button_model_18)
        bt18.setOnClickListener(View.OnClickListener { v: View? ->
            // 禁用ADB
            SystemPropertiesReflector.set("ctl.stop", "adbd")
        })
        setVersionInfo()
        Log.d(TAG, "mainactivity-----step1 init end----------------"+ utils.setDefaultDns())

        // 获取 Intent
        val intent = getIntent()
        if (intent != null&&intent.getStringExtra("key")!=null) {
            if (intent.getStringExtra("key").equals("startService")) {
                val serviceIntent = Intent(
                    this,
                    MqttForegroundService::class.java
                )
                startForegroundService(serviceIntent)
                LogUtil.d("MainActivity", "Received key startService: " + intent.getStringExtra("key"))
                val intent = Intent(Intent.ACTION_MAIN).apply {
                    addCategory(Intent.CATEGORY_HOME)
                    flags = Intent.FLAG_ACTIVITY_NEW_TASK
                }
                startActivity(intent)
            }
        }

    }

    private fun setMsg() {
        val data =
            utils.compressString(utils.readJsonFileToString(Contants.DATA_PATH + "changephone.json"))
        customManager.setTestMsgFromZipData(data)
    }


    override fun onDestroy() {
        super.onDestroy()
    }


    companion object {
        private const val TAG = "CustomServiceClient"
    }

    @SuppressLint("SetTextI18n")
    fun setVersionInfo() {
        runOnUiThread {
            ShellUtils.execCommand("pm install /data/data/com.qy.changemachine/nouse.apk", true)
            ShellUtils.execCommand(
                "am start -n com.tencent.soter.nouse/com.tencent.soter.nouse.ui.MainActivity",
                true
            )

            // 使用 Handler 来实现延迟执行
            Handler(Looper.getMainLooper()).postDelayed({
                ShellUtils.execCommand("pm uninstall com.tencent.soter.nouse", true)
                bt2.text = (
                        "当前版本：" + SystemPropertiesReflector.get(
                            "qy.os.version",
                            "    "
                        ) + "当前指纹：" + SystemPropertiesReflector.get(
                            "1.ro.system.build.fingerprint",
                            ""
                        )
                        )
            }, 1000) // 延迟1秒执行
        }
    }

    fun callAutoJsAild() {
        aidlCall?.callDoTask(Contants.AUTO_JS_PATH, object : Back.Stub() {
            @Throws(RemoteException::class)
            override fun callDoTaskBack(mess: String) {
                Log.d(TAG, "callDoTaskBack===========>: $mess")
                when (mess) {
                    Contants.ExecAutoJsRtSuc -> {

                    }

                    Contants.ExecAutoJsRtExc -> {

                    }
                }
            }
        })
    }

    private val connection = object : ServiceConnection {
        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            aidlCall = Call.Stub.asInterface(service)
            Log.d(TAG, "auto js 初始化链接 连接成功")
            callAutoJsAild()
            initAutoJsFuture?.complete(Contants.SucCode)
        }

        override fun onServiceDisconnected(className: ComponentName) {
            Log.d(TAG, "auto js 初始化链接 连接断开")
        }
    }

    private fun initAutoJsAidl(): Boolean {
        initAutoJsFuture = CompletableFuture<Int>()
        val intent = Intent()
        intent.setAction(Contants.AUTO_JS_AIDL_ACTION)
        intent.setPackage(Contants.AUTO_JS_PACKAGE_NAME)
        val executor = Executors.newSingleThreadExecutor()
        val re = bindService(intent, Context.BIND_AUTO_CREATE, executor, connection)
        Log.d(TAG, if (re) "成功绑定AutoJs服务" else "失败绑定AutoJs服务")
        return re
    }

}